package com.ryzx.jpa.helper.base;

import com.ryzx.common.response.BapException;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ryzx.common.response.BapResultCode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;


public class BapBaseServiceImpl<T extends BapBaseEntity, ID extends Serializable> implements BapBaseService<T,ID>{


    protected final JPAQueryFactory jpaQueryFactory;

    private final BapBaseRepository<T, ID> bapBaseRepository;

    public BapBaseServiceImpl(JPAQueryFactory jpaQueryFactory, BapBaseRepository<T, ID> bapBaseRepository) {
        this.jpaQueryFactory = jpaQueryFactory;
        this.bapBaseRepository = bapBaseRepository;
    }



    public Long count(Predicate t) {
        return bapBaseRepository.count(t);
    }


    public List<T> findAll(Predicate spec) {
        return (List<T>) bapBaseRepository.findAll(spec);
    }


    public List<T> findAll(Predicate spec, Sort sort) {
        return (List<T>) bapBaseRepository.findAll(spec,sort);
    }


    public Page<T> findAllToPage(Predicate predicate, Pageable page){
        return bapBaseRepository.findAll(predicate,page);
    }


    public <E extends BapBaseDTO> Page<T> findAllToPage(E e) {
        Pageable page= PageRequest.of(e.getPageNum() - 1,e.getPageSize());
        //TODO BapBaseDTO对象中各类查询参数未解决
        return bapBaseRepository.findAll(page);
    }


    public T save(T t){
        return bapBaseRepository.saveAndFlush(t);
    }

    public Optional<T> findById(ID id){
        if(id==null) return Optional.empty();
        return bapBaseRepository.findById(id);

    }

    public boolean del(T t){
        bapBaseRepository.delete(t);
        return true;
    }

    public boolean delById(ID id){
        bapBaseRepository.deleteById(id);
        return true;
    }

    public boolean delAll(Predicate spec){
        List<T> repositoryAll = (List<T>) bapBaseRepository.findAll(spec);
        bapBaseRepository.deleteAll(repositoryAll);
        return true;
    }


    public boolean delByIds(List<ID> ids) throws BapException {
        try {
            bapBaseRepository.deleteAllById(ids);
        }catch (Exception e){
           throw new BapException(BapResultCode.PARAM_NOT_VALID,"该记录删除失败");
        }
        return true;
    }
}
